<?php
/**
 * Created by PhpStorm.
 * User: wzy12
 * Date: 2018/10/29
 * Time: 17:41
 */

namespace app\common\model;


use think\Model;

class CouponList extends Model
{
    public function operation($data){
        // 优惠券类型
        $type = model('Coupon') -> where('id', $data['id']) -> value('type');

        // 获取发放数量和领取数量
        $coupon = model('Coupon') -> find($data['id']);

        $num = $coupon['send_num'];
        if(isset($data['users_id'])){
            $temp = [];
            foreach($data['users_id'] as $k => $v){
                $num++;
                $temp[] = ['cid' => $data['id'], 'send_time' => time(), 'uid' => $v, 'type' => $type];
            }
        }

        // 判断发往数量不足以让领取数量
        if($num > $coupon['createnum']){
            return echoArr(0, '优惠券数量不足以发放给这些用户');
        }

        $result = $this -> allowField(true) -> isUpdate(false) -> saveAll($temp);
        if(false === $result){
            return echoArr(0, $this -> getError());
        }else{
            model('Coupon') -> isUpdate(true) -> save(['id' => $data['id'], 'send_num' => $num]);

            return echoArr(1, '操作成功');
        }
    }

    public function resList($id){
        $join = [
            ['Coupon c', "cl.cid = $id"],
            ['Users u', 'u.id = cl.uid']
        ];

        $list = $this -> alias('cl') -> join($join) -> field('cl.*,c.name,u.username') -> paginate(10);

        // 订单列表
        $orders = model('Order') -> select();

        foreach ($list as $k => $v){
            foreach ($orders as $key => $val){
                if($v['order_id'] == $val['id']){
                    $list[$k]['order_sn'] = $val['order_sn'];
                }
            }
        }

        return $list;
    }

    public function del($data){
        // 更改领取数量
        $num = 0;
        if(is_array($data)){
            $cid = $this -> where('id', $data[0]) -> value('cid');

            $num += count($data);
        }else{
            $num = 1;
            $cid = $this -> where('id', $data) -> value('cid');
        }

        $send_num = model('Coupon') -> where('id', $cid) -> value('send_num');

        $result = $this -> destroy($data);

        model('Coupon') -> isUpdate(true) -> save(['id' => $cid, 'send_num' => $send_num - $num]);

        if(false === $result){
            return echoArr(0, '操作失败');
        }else{
            return echoArr(1, '操作成功');
        }
    }

    public function resFind($id){
        // 当前拥有优惠券用户
        $result = $this -> where('cid', $id) -> select();

        // 所有用户
        $users = model('Users') -> select();

        foreach($users as $k => $v){
            foreach($result as $key => $val){
                if($val['uid'] == $v['id']){
                    $users[$k]['checkbox'] = true;
                }
            }
        }

        return $users;
    }
}